﻿using System;
using System.Net;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Xml.Linq;
using Newtonsoft.Json;
using System.IO;
using System.Threading;
using Microsoft.Phone.Tasks;

namespace UI
{
    public delegate void OAuthCallback(HttpWebResponse response, XDocument xmlResult, object userState);

    public class MultipartData
    {
        public MultipartData(string fileName, Stream fileStream)
        {
            this.FileName = fileName;
            this.FileStream = fileStream;
        }

        public string FileName { get; private set; }
        public Stream FileStream { get; private set; }
    }

    public class OAuthHelper
    {
        private class ResponseState
        {
            public ResponseState(HttpWebRequest request, OAuthCallback callback, object userState)
            {
                this.Request = request;
                this.Callback = callback;
                this.UserState = userState;
            }

            public HttpWebRequest Request { get; private set; }
            public OAuthCallback Callback { get; private set; }
            public object UserState { get; private set; }
            public byte[] PostData { get; set; }
            public string ContentType { get; set; }
        }

        public static void PostProtectedResourceWithMultipart(APIInfo apiInfo, Dictionary<string, object> dataCollection, OAuthCallback callback, object userState)
        {
            CheckAccessTokenExpired();
            
            if (dataCollection != null && dataCollection.Count > 0)
            {
                string boundary = "*****";
                byte[] beginBoundary = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
                byte[] endBoundary = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
                byte[] lineEnd = Encoding.UTF8.GetBytes("\r\n");
                string stringDataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
                string fileDataHeaderTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
                MemoryStream memStream = new MemoryStream();
                byte[] buffer = new byte[1024];
                int bytesRead;
                foreach (KeyValuePair<string, object> item in dataCollection)
                {
                    memStream.Write(beginBoundary, 0, beginBoundary.Length);
                    if (item.Value is string)
                    {
                        string value = item.Value as string;
                        //string stringData = string.Format(stringDataTemplate, item.Key, HttpUtility.UrlEncode(value));
                        string stringData = string.Format(stringDataTemplate, item.Key, value);
                        byte[] data = Encoding.UTF8.GetBytes(stringData);
                        memStream.Write(data, 0, data.Length);
                    }
                    else
                    {
                        MultipartData value = item.Value as MultipartData;
                        string contentType = string.Empty;
                        string extension = Path.GetExtension(value.FileName);
                        switch (extension)
                        {
                            case ".jpeg":
                            case ".jpg":
                            case ".jpe":
                                contentType = "image/jpeg";
                                break;
                            case ".gif":
                                contentType = "image/gif";
                                break;
                            case ".png":
                                contentType = "image/x-png";
                                break;
                        }
                        string fileDataHeader = string.Format(fileDataHeaderTemplate, item.Key, value.FileName, contentType);
                        byte[] data = Encoding.UTF8.GetBytes(fileDataHeader);
                        memStream.Write(data, 0, data.Length);
                        
                        while ((bytesRead = value.FileStream.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            memStream.Write(buffer, 0, bytesRead);
                        }
                        value.FileStream.Close();
                        memStream.Write(lineEnd, 0, lineEnd.Length);
                    }
                }
                memStream.Write(endBoundary, 0, endBoundary.Length);
                byte[] postData = memStream.ToArray();
                memStream.Close();

                HttpWebRequest request = WebRequest.CreateHttp(new Uri(apiInfo.APIUrl, UriKind.Absolute));
                request.Headers["Authorization"] = "OAuth2 " + ConfigHelper.AccessToken;
                request.Method = apiInfo.APIMethod;
                ResponseState state = new ResponseState(request, callback, userState);
                state.PostData = postData;
                state.ContentType = "multipart/form-data; boundary=" + boundary;
                request.BeginGetRequestStream(RequestStreamCallback, state);
            }
        }

        public static void AccessProtectedResource(APIInfo apiInfo, Dictionary<string, string> dataCollection, OAuthCallback callback, object userState)
        {
            CheckAccessTokenExpired();

            // Resolve the URL caching issue
            if (apiInfo.APIMethod == "GET")
            {
                if (dataCollection == null)
                {
                    dataCollection = new Dictionary<string, string>();
                }
                dataCollection.Add("fix_urlcaching", DateTimeOffset.Now.Ticks.ToString());
            }

            string url = apiInfo.APIUrl;
            string data = string.Empty;
            if (dataCollection != null && dataCollection.Count > 0)
            {
                StringBuilder builder = new StringBuilder();
                foreach (KeyValuePair<string, string> item in dataCollection)
                {
                    builder.Append(item.Key + "=" + HttpUtility.UrlEncode(item.Value) + "&");
                }
                data = builder.ToString().TrimEnd('&');
                if (apiInfo.APIMethod == "GET")
                {
                    url = url + "?" + data;
                }
            }

            HttpWebRequest request = WebRequest.CreateHttp(new Uri(url, UriKind.Absolute));
            request.Headers["Authorization"] = "OAuth2 " + ConfigHelper.AccessToken;
            request.Method = apiInfo.APIMethod;
            ResponseState state = new ResponseState(request, callback, userState);

            if (apiInfo.APIMethod == "POST" && data != string.Empty)
            {
                byte[] bytes = Encoding.UTF8.GetBytes(data);
                state.PostData = bytes;
                state.ContentType = "application/x-www-form-urlencoded";
                request.BeginGetRequestStream(RequestStreamCallback, state);
                return;
            }

            IAsyncResult ar = request.BeginGetResponse(ResponseCallback, state);

            Thread thread = new Thread(TimeoutCallback);
            thread.Start(ar);
        }

        private static void TimeoutCallback(object state)
        {
            IAsyncResult ar = state as IAsyncResult;
            ResponseState responseState = ar.AsyncState as ResponseState;
            Thread.Sleep(ConfigHelper.RequestMillisecondsTimeout);
            if (ar.IsCompleted == false)
            {
                responseState.Request.Abort();
            }
        }

        private static void RequestStreamCallback(IAsyncResult asyncResult)
        {
            ResponseState state = asyncResult.AsyncState as ResponseState;
            HttpWebRequest request = state.Request;
            request.ContentType = state.ContentType;

            Stream stream = request.EndGetRequestStream(asyncResult);
            stream.Write(state.PostData, 0, state.PostData.Length);
            stream.Close();

            IAsyncResult ar = request.BeginGetResponse(ResponseCallback, state);

            Thread thread = new Thread(TimeoutCallback);
            thread.Start(ar);
        }

        private static void ResponseCallback(IAsyncResult asyncResult)
        {
            ResponseState state = asyncResult.AsyncState as ResponseState;
            HttpWebResponse response = null;
            try
            {
                response = state.Request.EndGetResponse(asyncResult) as HttpWebResponse;
            }
            catch (WebException ex)
            {
                ex.Data.Add("RequestUri", state.Request.RequestUri.AbsoluteUri);
                response = ex.Response as HttpWebResponse;
                if (response != null)
                {
                    if (response.StatusCode == HttpStatusCode.BadRequest)
                    {
                        if (response.Headers["Content-Type"].Contains("application/json") == true)
                        {
                            Stream stream = response.GetResponseStream();
                            StreamReader streamRead = new StreamReader(stream);
                            string jsonResult = streamRead.ReadToEnd();
                            ex.Data.Add("BadRequestContent", jsonResult);
                        }
                    }
                }
                throw;
            }
            
            XDocument xmlResult = null;
            if (state.Callback != null)
            {
                if (response.Headers["Content-Type"].Contains("application/json") == true)
                {
                    Stream stream = response.GetResponseStream();
                    StreamReader streamRead = new StreamReader(stream);
                    string jsonResult = streamRead.ReadToEnd();
                    xmlResult = JsonConvert.DeserializeXNode(jsonResult, "root");
                }
            }

            response.Close();

            if (state.Callback != null)
            {
                state.Callback(response, xmlResult, state.UserState);
            }
        }

        private static void CheckAccessTokenExpired()
        {
            if (ConfigHelper.AccessTokenExpiredTime < DateTimeOffset.Now)
            {
                CommonHelper.ShowErrorMessage("登录有效期已过，请重新登录！");
                (Application.Current as App).RootFrame.Navigate(new Uri("/Authentication.xaml", UriKind.Relative));
            }
        }
    }
}
